"""
Case Type   : datakit安装
Case Name   : 在系统直接删除log文件
Create At   : 2025/4/21
Owner       : @lonely-dance
Description :
    1.查看当前的log文件
    2.在服务上删除log文件
    3.查看前端log文件是否存在
    4.恢复环境
Expect      :
    1.成功
    2.成功
    3.成功
    4.成功
History     :
"""

import os
import re
import time
import unittest

from yat.test import Node
from yat.test import macro
from testcase.utils.Logger import Logger
from testcase.utils.CommonSH import CommonSH
from testcase.utils.datakit_api.CommonApi import CommonApi


class Tools(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f"-----{os.path.basename(__file__)} start-----")
        self.com_sh = CommonSH()
        self.datakit_node = Node('Datakit_Root')
        self.token = self.com_sh.get_token_value(macro.DATAKIT_PASSWD)
        self.log.info(self.token)
        self.assertNotEqual("error", self.token)
        self.com_api = CommonApi(self.token)

    def test_base_ops(self):
        text = '----step1:查看当前log文件 expect:成功----'
        self.log.info(text)
        response = self.com_api.get_system_log_files()
        self.log.info(response.json())
        self.assertIsNotNone(response.json()['data'], '执行失败')

        text = '----step2:在服务上删除log文件 expect:成功----'
        self.log.info(text)
        del_cmd = f'''cd {macro.DATAKIT_INSTALL_PATH};rm -rf logs/*;'''
        del_res = self.datakit_node.sh(del_cmd).result()
        self.log.info(del_res)
        self.assertEqual('', del_res, '删除文件失败')

        text = '----step3:查看前端log文件是否存在 expect:成功'
        self.log.info(text)
        response = self.com_api.get_system_log_files()
        self.log.info(response.json())
        self.assertEqual([], response.json()['data'], '执行失败')

    def tearDown(self):
        self.log.info('----step4:恢复环境----')
        cmd = f'cd {macro.DATAKIT_INSTALL_PATH};sh run.sh restart;'
        res = self.datakit_node.sh(cmd).result()
        self.log.info(res)
        self.assertIn('Datakit started.', res, '恢复环境失败')
        time.sleep(60)
        cmd = f'cd {macro.DATAKIT_INSTALL_PATH};sh run.sh status;'
        res = self.datakit_node.sh(cmd).result()
        self.log.info(res)
        self.assertIn('Datakit is running', res, '恢复环境失败')
        self.log.info(f"-----{os.path.basename(__file__)} finsh-----")
